package cn.tedu.csmall.resource.controller;


import cn.tedu.csmall.resource.exception.ServiceException;
import cn.tedu.csmall.resource.pojo.vo.UploadResult;
import cn.tedu.csmall.resource.web.JsonResult;
import cn.tedu.csmall.resource.web.ServiceCode;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/resources")
@Api(tags = "文件上传模块")
public class ResourceController {
    @Value("${imagesPath}")
    private String dirPath;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    @ApiOperationSupport(order = 100)
    public JsonResult upload(@RequestParam MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            String message = "上传商品图片失败，请选择您要上传的文件！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPLOAD_EMPTY, message);
        }

        String fileName=file.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        fileName= UUID.randomUUID()+suffix;
        SimpleDateFormat format=new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath=format.format(new Date());
        File dirFile=new File(dirPath+datePath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        file.transferTo(new File(dirPath+datePath+fileName));
        UploadResult uploadResult=new UploadResult();
        uploadResult.setContentType(file.getContentType());
        uploadResult.setFileSize(file.getSize());
        uploadResult.setFileName(fileName);
        return JsonResult.ok(uploadResult);
    }
}
